package _12_回溯;


import java.util.*;

public class _90_子集II {

    public static void main(String[] args) {
        _90_子集II v = new _90_子集II();
        int[] ins = new int[]{4, 4, 4, 1, 4};
        List<List<Integer>> subsets = v.subsetsWithDup(ins);
        for (List<Integer> subset : subsets) {
            System.out.println(subset);
        }
    }

    // 利用取重写法, 如果是排列去重，那么可以使用排序，看是否相等即可
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        // 排序
        Arrays.sort(nums);
        dfs(results, nums, 0, new ArrayList<>());
        return new ArrayList<>(results);
    }

    private void dfs(List<List<Integer>> results, int[] nums, int index, List<Integer> tempStore) {
        results.add(new ArrayList<>(tempStore));
        for (int i = index; i < nums.length; i++) {
            // 如果当前值，和前面值相同，直接跳过
            if (i > index && nums[i] == nums[i - 1]) {
                continue;
            }
            tempStore.add(nums[i]);
            dfs(results, nums, i + 1, tempStore);
            // 回溯
            tempStore.remove(tempStore.size() - 1);
        }
    }


    // 利用取重写法
    public List<List<Integer>> subsetsWithDup1(int[] nums) {
        Set<List<Integer>> results = new HashSet<>();
        Arrays.sort(nums);
        dfs1(results, nums, 0, new ArrayList<>());
        return new ArrayList<>(results);
    }

    private void dfs1(Set<List<Integer>> results, int[] nums, int i, List<Integer> tempStore) {

        results.add(new ArrayList<>(tempStore));

        for (int j = i; j < nums.length; j++) {
            tempStore.add(nums[j]);
            dfs1(results, nums, j + 1, tempStore);
            // 回溯
            tempStore.remove(tempStore.size() - 1);
        }
    }

}
